package com.wanli.service.impl;

import com.wanli.common.Result;
import com.wanli.domain.entity.Category;
import com.wanli.domain.entity.SysGoodsCategoryBusiness;
import com.wanli.domain.vo.DictVo;
import com.wanli.mapper.CategoryMapper;
import com.wanli.mapper.GoodsMapper;
import com.wanli.mapper.SysGoodsCategoryBusinessMapper;
import com.wanli.service.CategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Byterain
 * @since 2024-11-01
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Resource
    private CategoryMapper categoryMapper;
    @Resource
    private GoodsMapper goodsMapper;
    @Resource
    private SysGoodsCategoryBusinessMapper sysGoodsCategoryBusinessMapper;

    @Override
    public Result getCategoryCount() {
        // 按categoryId分组,统计数量
        Map<Long, Long> numCount = sysGoodsCategoryBusinessMapper.selectList(null)
                .stream()
                .collect(Collectors.groupingBy(SysGoodsCategoryBusiness::getCategoryId, Collectors.counting()));
        // 转化CategoryId为categoryName
        List<DictVo> list = new ArrayList<>();
        numCount.forEach((categoryId, goodsCount) -> {
            Category category = categoryMapper.selectById(categoryId);
            DictVo vo = new DictVo();
            vo.setLabel(category.getCategoryName());
            vo.setValue(goodsCount.toString());
            list.add(vo);
        });
        return Result.success(list);
    }
}
